package com.raising.modules.code.controller;

import com.google.common.collect.Lists;
import com.raising.modules.code.config.Config;
import com.raising.modules.code.entity.TableModel;
import com.raising.modules.code.entity.TreeNodeVo;
import com.raising.modules.code.service.DbService;
import com.raising.modules.code.utils.db.DBManger;
import com.raising.modules.code.utils.db.DBMangerPool;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.springframework.web.bind.annotation.*;

import com.raising.framework.controller.BaseController;
import com.raising.framework.entity.ResultVo;
import com.raising.framework.interceptor.Page;
import com.raising.modules.sys.utils.DictUtils;

import com.raising.utils.JStringUtils;

import com.raising.modules.code.entity.CodePool;
import com.raising.modules.code.service.CodePoolService;

import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import java.util.List;

/**
 * 资源池 控制器
 * @author gaoyuan
 * @createTime 2018-01-02 20:26:14
 */
@Controller
@RequestMapping("${adminPath}/code/codePool")
public class CodePoolController extends BaseController {

    @Autowired
    private CodePoolService codePoolService;
    /**
     * 获取单个对象（共用）
     * @author gaoyuan
     * @createTime 2018-01-02 20:26:14
     */
    @ModelAttribute
    public CodePool get(@RequestParam(required = false) String id) {
        CodePool entity = null;
        if (JStringUtils.isNotBlank(id)) {
            entity = codePoolService.get(id);
        }
        if (entity == null) {
            entity = new CodePool();
        }
        return entity;
    }
    /**
    * 跳转至列表页面
    * @author gaoyuan
    * @createTime 2018-01-02 20:26:14
    */
    @RequiresPermissions("code:codePool:view")
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public String list() {
        return "code/codePool/list";
    }

    /**
    * 加载列表分页数据
    * @author gaoyuan
    * @createTime 2018-01-02 20:26:14
    */
    @RequiresPermissions("code:codePool:view")
    @RequestMapping(value = "/getPage.json", method = RequestMethod.POST)
    public @ResponseBody ResultVo getPage(Model model, CodePool codePool,Page<CodePool> page) {
        page.setEntity(codePool);
        page.setOrderBy(" a.id asc ");
        return new ResultVo(ResultVo.SUCCESS,"ok",codePoolService.getPage(page));
    }

    /**
    * 跳转新增页面
    * @author gaoyuan
    * @createTime 2018-01-02 20:26:14
    */
    @RequiresPermissions("code:codePool:create")
    @RequestMapping(value = "/create", method = RequestMethod.GET)
    public String create(CodePool codePool,Model model) {
        model.addAttribute("codePool", codePool);
        // 是否可用
        model.addAttribute("yn", DictUtils.getDictList("DIM_YN"));
        return "code/codePool/add";
    }

    /**
    * 执行新增操作
    * @author gaoyuan
    * @createTime 2018-01-02 20:26:14
    */
    @RequiresPermissions("code:codePool:create")
    @RequestMapping(value = "/create", method = RequestMethod.POST)
    public String create(CodePool codePool, RedirectAttributes redirectAttributes) {
        codePoolService.save(codePool);
        addMessage(redirectAttributes,"新增成功");
        return "redirect:"+ adminPath +"/code/codePool/update?id="+codePool.getId();
    }
    /**
    * 跳转更新页面
    * @author gaoyuan
    * @createTime 2018-01-02 20:26:14
    */
    @RequiresPermissions("code:codePool:update")
    @RequestMapping(value = "/update", method = RequestMethod.GET)
    public String update(CodePool codePool, Model model) {
        model.addAttribute("codePool", codePool);
        // 是否可用
        model.addAttribute("yn", DictUtils.getDictList("DIM_YN"));
        return "code/codePool/edit";
    }
    /**
    * 执行更新操作
    * @author gaoyuan
    * @createTime 2018-01-02 20:26:14
    */
    @RequiresPermissions("code:codePool:update")
    @RequestMapping(value = "/update", method = RequestMethod.POST)
    public String update(CodePool codePool, RedirectAttributes redirectAttributes) {
        codePoolService.save(codePool);
        addMessage(redirectAttributes,"修改成功");
        return "redirect:"+ adminPath +"/code/codePool/update?id="+codePool.getId();
    }
    /**
    * 执行删除操作
    * @author gaoyuan
    * @createTime 2018-01-02 20:26:14
    */
    @RequiresPermissions("code:codePool:delete")
    @RequestMapping(value = "/delete", method = RequestMethod.GET)
    public String delete(String id,int pageNo,int pageSize, RedirectAttributes redirectAttributes) {
        codePoolService.delete(id);
        addMessage(redirectAttributes,"删除成功");
        return "redirect:"+ adminPath +"/code/codePool/list?pageNo="+pageNo+"&pageSize="+pageSize;
    }
    DbService dbService = new DbService();
    /**
     * 根据资源池标识查询数据库与表列表
     * @author GaoYuan
     * @datetime 2018/1/4 下午3:17
     */
    @RequiresPermissions("code:codePool:view")
    @RequestMapping(value = "/getTableList.json", method = RequestMethod.POST)
    public @ResponseBody ResultVo getTableList(Model model, String poolId) {
        CodePool pool = codePoolService.get(poolId);

        List<TreeNodeVo> treeList = Lists.newArrayList();
        //顶级
        treeList.add(new TreeNodeVo("1","0","数据库","0"));
        //先查询数据库

        DBManger dBManger = new DBManger(pool.getIp()+":"+pool.getPort(),pool.getUsername(),pool.getPassword());
        DBMangerPool dBMangerPool = DBMangerPool.getInstance();
        dBMangerPool.setDbMangerPools(Config.dbKey, dBManger);
        List<String> dbs = dbService.getDatabase(Config.dbKey);
        for (int j = 0; j < dbs.size(); j++) {
            System.out.println("dbs.get(j)="+dbs.get(j));
            treeList.add(new TreeNodeVo("D-"+dbs.get(j),"1",dbs.get(j),"0"));
            //再查看数据库下面的所有表
            List<TableModel> tables = dbService.getTables(Config.dbKey, dbs.get(j));
            for (int k = 0; k < tables.size(); k++) {
                String desc = tables.get(k).getTableDesc();
                desc = desc.replaceAll("\r","");
                desc = desc.replaceAll("\n","");
                treeList.add(new TreeNodeVo("T-"+poolId+"-"+dbs.get(j)+"-"+tables.get(k).getTableName(),"D-"+dbs.get(j),tables.get(k).getTableName() + "(" + desc + ")","1"));
            }
        }

        return new ResultVo(ResultVo.SUCCESS,"ok",treeList);
    }

}
